<?php
/**
 * Created by PhpStorm.
 * User: JYuans
 * Date: 2019/12/1
 * Time: 10:41
 */
namespace Bstage\Controller;

use Common\Model\CommonModel;

class MidExamineUpRelationController extends BstageController {

    /**
     * 设置中层考核上级关系
     */
    public function addRelationAction(){
        $mid_ex_id = $_REQUEST['mid_ex_id']?$_REQUEST['mid_ex_id']:$this->errorReturn("缺少中层考核ID");
        $user_id = $_REQUEST['user_id']?$_REQUEST['user_id']:$this->errorReturn("缺少考核人ID");
        $up_relation_json = $_REQUEST['up_relation_json']?$_REQUEST['up_relation_json']:$this->errorReturn("缺少上级关系JSON");

        $up_relation_array = json_decode($up_relation_json,true);

        if(!is_array($up_relation_array)){
            $this->errorReturn("上级关系JSON格式错误");
        }

        $model = M();
        $model->startTrans();

        if($up_relation_array){
            $count_100 = 0;
            for($i=0;$i<count($up_relation_array);$i++){
                if(count($up_relation_array[$i]) != 2 || !is_numeric($up_relation_array[$i][0]) || !is_numeric($up_relation_array[$i][1])){
                    $this->errorReturn("上级关系JSON格式错误");
                }

                $count_100 += $up_relation_array[$i][1];
            }
            //判断权重之和
            if($count_100 != 100){
                $this->errorReturn("权重之和必须等于100");
            }

            //获取修改的用户ID数组
            $edit_up_user_id_array = array_column($up_relation_array,0);
            //获取修改的上级权重数组
            $edit_up_user_weight_array = array_column($up_relation_array,1);

            //修改 [用户ID]=>[权重];
            $user_id_weight_array = array_combine($edit_up_user_id_array,$edit_up_user_weight_array);

            //判断上级ID，顺便获取上级等级
            $user_list = M("User")
                ->where(['user_id'=>['in',$edit_up_user_id_array]])
                ->getField("user_id,rank");
            foreach($user_list as $key=>$value){
                if($value != 4 && $value != 5){
                    $this->errorReturn("上级ID错误");
                }
            }

            //获取已添加的上级审核关系
            $all_up_user_id_array = M("MidExamineUpRelation")
                ->where(['mid_ex_id'=>$mid_ex_id,'be_examine_user_id'=>$user_id])
                ->getField("examine_user_id",true);

            if($all_up_user_id_array){
                //需要添加上层评审关系
                $need_add_user_id_array = array_values(array_diff($edit_up_user_id_array,$all_up_user_id_array));
                for($i=0;$i<count($need_add_user_id_array);$i++){
                    $new_relation_data = array();
                    $new_relation_data['mid_ex_id'] = $mid_ex_id;
                    $new_relation_data['be_examine_user_id'] = $user_id;
                    $new_relation_data['examine_user_id'] = $need_add_user_id_array[$i];
                    $new_relation_data['up_type'] = $user_list[$need_add_user_id_array[$i]]==4?1:0;
                    $new_relation_data['weight'] = bcdiv($user_id_weight_array[$need_add_user_id_array[$i]],100,2);

                    $add_relation_result = M("MidExamineUpRelation")
                        ->add($new_relation_data);
                    if(!$add_relation_result){
                        $model->rollback();
                        $this->errorReturn("添加审核关系失败，请重新尝试");
                    }
                }

                //需要修改的权重关系
                $need_edit_user_id_array = array_values(array_intersect($edit_up_user_id_array,$all_up_user_id_array));
                for($i=0;$i<count($need_edit_user_id_array);$i++){
                    $new_relation_data['weight'] = bcdiv($user_id_weight_array[$need_edit_user_id_array[$i]],100,2);

                    $edit_relation_result = M("MidExamineUpRelation")
                        ->where(['mid_ex_id'=>$mid_ex_id,'be_examine_user_id'=>$user_id,'examine_user_id'=>$need_edit_user_id_array[$i]])
                        ->save($new_relation_data);
                }

                //需要删除上层评审关系
                $need_delete_user_id_array = array_values(array_diff($all_up_user_id_array,$edit_up_user_id_array));
                if($need_delete_user_id_array){
                    $delete_relation_result = M("MidExamineUpRelation")
                        ->where(['mid_ex_id'=>$mid_ex_id,'be_examine_user_id'=>$user_id,'examine_user_id'=>['in',$need_delete_user_id_array]])
                        ->delete();
                    if(!$delete_relation_result){
                        $model->rollback();
                        $this->errorReturn("设置审核关系失败，请重新尝试");
                    }
                }
            }else{
                for($i=0;$i<count($up_relation_array);$i++){
                    $new_relation_data = array();
                    $new_relation_data['mid_ex_id'] = $mid_ex_id;
                    $new_relation_data['be_examine_user_id'] = $user_id;
                    $new_relation_data['examine_user_id'] = $up_relation_array[$i][0];
                    $new_relation_data['up_type'] = $user_list[$up_relation_array[$i][0]]==4?1:0;
                    $new_relation_data['weight'] = bcdiv($up_relation_array[$i][1],100,2);

                    $add_relation_result = M("MidExamineUpRelation")
                        ->add($new_relation_data);
                    if(!$add_relation_result){
                        $model->rollback();
                        $this->errorReturn("添加审核关系失败，请重新尝试");
                    }
                }
            }
        }else{
            //mid_ex_id,be_examine_user_id
            $relation_count = M("MidExamineUpRelation")
                ->where(['mid_ex_id'=>$mid_ex_id,'be_examine_user_id'=>$user_id])
                ->count();
            if($relation_count){
                $delete_relation_result = M("MidExamineUpRelation")
                    ->where(['mid_ex_id'=>$mid_ex_id,'be_examine_user_id'=>$user_id])
                    ->delete();
                if(!$delete_relation_result){
                    $model->rollback();
                    $this->errorReturn("修改设置失败，请重新尝试");
                }
            }else{
                $model->rollback();
                $this->errorReturn("请选择要设置的上级考核关系");
            }
        }

        $model->commit();
        $this->successReturn("设置成功");
    }

    /**
     * 考核结果列表接口
     */
    public function examineResultList(){
        //必要参数
        $mid_ex_id = $_REQUEST['mid_ex_id']?$_REQUEST['mid_ex_id']:$this->errorReturn("缺少中层考核ID");

        //分页
        $now_page = $_REQUEST['now_page']?$_REQUEST['now_page']:1;//默认第一页
        $page_size = $_REQUEST['page_size']?$_REQUEST['page_size']:50;//默认每页50条

        //查询条件
        $where = array();
        //筛选中层员工
        if($_REQUEST["search_user_id"]){
            $where['user_id'] = $_REQUEST["search_user_id"];
        }
        //筛选级别
        if($_REQUEST["search_rank"] == 3 || $_REQUEST["search_rank"] == 4){
            $where['rank'] = $_REQUEST["search_rank"];
        }else{
            $where['rank'] = ['in','3,4'];
        }
        //筛选干部名称
        if($_REQUEST["search_name"]){
            $where['name'] = ['like','%'.$_REQUEST['search_name'].'%'];
        }
        //筛选职务
        if($_REQUEST["search_station"]){
            $where['station'] = ['like','%'.$_REQUEST['search_station'].'%'];
        }

        $field = "user_id,depart_id,name,rank,station";

        $list_data = M("User")
            ->where($where)
            ->page($now_page,$page_size)
            ->order("user_id")
            ->field($field)
            ->select();

        if(!$list_data){
            $this->returnJson(503,"无数据");
        }

        $depart_id_array = array_column($list_data,"depart_id");
        $depart_name_array = M("Department")
            ->where(['depart_id'=>['in',$depart_id_array]])
            ->getField("depart_id,name");

        $up_user_data = M("User")
            ->where(['rank'=>5])
            ->getField("user_id,name,rank");

        foreach($list_data as $key=>$value){
            $list_data[$key]['depart_name'] = $depart_name_array[$value['depart_id']];
            $list_data[$key]['rank'] = CommonModel::rank_str_array[$value['rank']];

            $examine_result = M("MidExamineUpRelation")
                ->where(['mid_ex_id'=>$mid_ex_id,'be_examine_user_id'=>$value['user_id']])
                ->field("examine_user_id,status,up_type,weight,score,weight_score")
                ->order('up_type')          //确保直接上级在循环中处于末尾
                ->select();
            $superior_score = $up_user_data;
            $direct_superior_score = array();
            //初始化数据
            foreach($superior_score as $key2=>$value2){
                $superior_score[$key2]['score'] = "";
                $superior_score[$key2]['weight'] = "";
            }
            $amount_score = 0;
            foreach($examine_result as $key2=>$value2){
                if($value2['up_type'] == 0){
                    if(isset($superior_score[$value2['examine_user_id']])){
                        $superior_score[$value2['examine_user_id']]['score'] = $value2['status']==1?floatval($value2['score']):"未评审";
                        $superior_score[$value2['examine_user_id']]['weight'] = $value2['status']==1?bcmul($value2['weight'],100)."%":"未评审";

                        $amount_score = bcadd($amount_score,$value2['weight_score'],4);
                    }
                }else{
                    $new_direct_superior_data = array();
                    $new_direct_superior_data['name'] = M("User")
                        ->where(['user_id'=>$value2['examine_user_id']])
                        ->getField("name");
                    $new_direct_superior_data['score'] = $value2['status']==1?floatval($value2['score']):"未评审";
                    $new_direct_superior_data['weight'] = $value2['status']==1?bcmul($value2['weight'],100)."%":"未评审";
                    $direct_superior_score[] = $new_direct_superior_data;

                    $amount_score = bcadd($amount_score,$value2['weight_score'],4);
                }
            }
            $list_data[$key]['superior_score_list'] = array_values($superior_score);
            $list_data[$key]['direct_superior_score_list'] = $direct_superior_score;
            $list_data[$key]['score'] = round($amount_score,2);
        }

        $count = M("User")
            ->where($where)
            ->count();

        $return_data = array();
        $return_data['list_data'] = $list_data;
        $return_data['up_user_data'] = array_values($up_user_data);
        $return_data['count'] = $count;
        $return_data['now_page'] = $now_page;
        $return_data['page_size'] = $page_size;
        $return_data['max_page'] = ceil($count / $page_size);

        $this->successReturn("获取成功",$return_data);
    }

    /**
     * 获取得分汇总列表接口
     */
    public function scoreDetailsList(){
        //必要参数
        $mid_ex_id = $_REQUEST['mid_ex_id']?$_REQUEST['mid_ex_id']:$this->errorReturn("缺少中层考核ID");
        //分页
        $now_page = $_REQUEST['now_page']?$_REQUEST['now_page']:1;//默认第一页
        $page_size = $_REQUEST['page_size']?$_REQUEST['page_size']:50;//默认每页50条
        //查询条件
        $where = array();
        $where['dr.mid_ex_id'] = $mid_ex_id;
        $where['dr.status'] = 1;
        //筛选级别
        if($_REQUEST["search_user_id"]){
            $where['u.user_id'] = $_REQUEST["search_user_id"];
        }
        //筛选级别
        if($_REQUEST["search_rank"]){
            $where['u.rank'] = $_REQUEST["search_rank"];
        }
        //筛选干部名称
        if($_REQUEST["search_name"]){
            $where['u.name'] = ['like','%'.$_REQUEST['search_name'].'%'];
        }
        //筛选职务
        if($_REQUEST["search_station"]){
            $where['u.station'] = ['like','%'.$_REQUEST['search_station'].'%'];
        }

        //筛选考评人姓名
        if($_REQUEST["search_examine_user_name"]){
            $search_examine_user_id = M("User")
                ->where(['name'=>['like','%'.$_REQUEST["search_examine_user_name"].'%']])
                ->getField("user_id",true);
            $where['dr.examine_user_id'] = ['in',$search_examine_user_id];
        }

        $field = "u.user_id,u.depart_id,u.name,u.rank,u.station,dr.examine_time,dr.examine_result,dr.score,dr.examine_user_id";

        $list_data = M("MidExamineUpRelation")
            ->alias("dr")
            ->join("__USER__ u on dr.be_examine_user_id = u.user_id")
            ->where($where)
            ->field($field)
            ->page($now_page,$page_size)
            ->select();

        if(!$list_data){
            $this->returnJson(503,"无数据");
        }

        $depart_id_array = array_column($list_data,"depart_id");
        $depart_name_array = M("Department")
            ->where(['depart_id'=>['in',$depart_id_array]])
            ->getField("depart_id,name");

        $examine_user_id_array = array_column($list_data,"examine_user_id");
        $examine_user_name_array = M("User")
            ->where(['user_id'=>['in',$examine_user_id_array]])
            ->getField("user_id,name");

        foreach($list_data as $key=>$value){
            $list_data[$key]['score'] = floatval($value['score']);

            $list_data[$key]['depart_name'] = $depart_name_array[$value['depart_id']];

            $list_data[$key]['examine_user_name'] = $examine_user_name_array[$value['examine_user_id']];

            $list_data[$key]['rank'] = CommonModel::rank_str_array[$value['rank']];

            $list_data[$key]['examine_time'] = changeDateTime($value['examine_time']);

            $list_data[$key]['examine_result'] = json_decode($value['examine_result'],true);
        }

        $count = M("MidExamineUpRelation")
            ->alias("dr")
            ->join("__USER__ u on dr.be_examine_user_id = u.user_id")
            ->where($where)
            ->count();

        $examine_title_list = M("MidExamineItem")
            ->where(['mid_ex_id'=>$mid_ex_id])
            ->getField("title",true);

        $return_data = array();
        $return_data['list_data'] = $list_data;
        $return_data['examine_title_list'] = $examine_title_list;
        $return_data['count'] = $count;
        $return_data['now_page'] = $now_page;
        $return_data['page_size'] = $page_size;
        $return_data['max_page'] = ceil($count / $page_size);

        $this->successReturn("获取成功",$return_data);
    }
}